package cn.com.fattiger.framework.remoting.netty4.common;

import java.util.Map;

import cn.com.fattiger.framework.remoting.netty4.client.ResponseFuture;
import cn.com.fattiger.framework.remoting.netty4.client.channel.GlobalClientChannelManager;
import cn.com.fattiger.framework.remoting.netty4.common.channel.ChannelManager;

public class RPC {

	public static void async(String url, int timeout, Map<String, Object> params, ICallback callback) throws Exception {
		ChannelManager channel = GlobalClientChannelManager.get(url);
		if (null == channel) {
			return;// no connection valid.
		}
		Invocation request = new Invocation();
		request.setRequest(params.toString());
		channel.setTransferTime(System.currentTimeMillis());
		System.out.println("channel.getChannel()=" + channel.getChannel() + "\trequest=" + request);
		channel.getChannel().writeAndFlush(request).sync();
		new ResponseFuture(channel, request, timeout, callback);
	}

	public static Object sync(String url, int timeout, Map<String, Object> params, ICallback callback) throws Exception {
		ChannelManager channel = GlobalClientChannelManager.get(url);
		if (null == channel) {
			return null;// no connection valid.
		}
		Invocation request = new Invocation();
		request.setRequest(params.toString());
		channel.setTransferTime(System.currentTimeMillis());
		System.out.println("channel.getChannel()=" + channel.getChannel() + "\trequest=" + request);
		channel.getChannel().writeAndFlush(request).sync();
		ResponseFuture response = new ResponseFuture(channel, request, timeout, callback);
		return response.get(timeout);
	}
}
